package com.chb.filter;

import com.chb.common.CommonConstants;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springframework.core.annotation.Order;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.UUID;

/**
 * @description: 设置追踪id
 * @author: chb
 * @create: 2022-05-24 17:39
 **/
@Slf4j
@Order(Integer.MIN_VALUE)
@WebFilter(filterName="logFilter", urlPatterns="/*")
public class LogFilter extends OncePerRequestFilter {

    /**
     * 由于fegin开启了hystrix支持导致追踪id失效
     * @author CHB
     * @date 2022-08-19 14:24:20
     */
    @Override
    protected void doFilterInternal(HttpServletRequest servletRequest, HttpServletResponse servletResponse, FilterChain filterChain) throws ServletException, IOException {
        String traceId = servletRequest.getHeader(CommonConstants.TRACE_ID);
        if(StringUtils.isEmpty(traceId)){
            traceId = UUID.randomUUID().toString().replace("-","");
        }
        MDC.put(CommonConstants.TRACE_ID,traceId);
        String uri  = servletRequest.getRequestURI();
        long start = System.currentTimeMillis();
        log.info("请求地址:{}, 开始时间:{}", uri, start);
        filterChain.doFilter(servletRequest, servletResponse);
        log.info("请求地址:{}, 请求耗时:{}", uri, (System.currentTimeMillis() - start));
        MDC.remove(CommonConstants.TRACE_ID);
    }
}
